<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="`业主房户关联 - ${ownerData?.ownerName || ''}`"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="owner-household-container">
      <!-- 业主信息展示 -->
      <el-card class="owner-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>业主基本信息</span>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="业主姓名">{{ ownerData?.ownerName }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ ownerData?.idCard }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ ownerData?.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱地址">{{ ownerData?.email }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            <el-tag :type="ownerData?.gender === 1 ? 'primary' : ownerData?.gender === 2 ? 'success' : 'info'">
              {{ ownerData?.gender === 1 ? '男' : ownerData?.gender === 2 ? '女' : '未知' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="ownerData?.status === 1 ? 'success' : 'danger'">
              {{ ownerData?.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 房户关联列表 -->
      <el-card class="household-list-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>关联房户列表</span>
            <el-button type="primary" size="small" @click="handleAddHousehold">
              <el-icon><Plus /></el-icon>
              新增关联
            </el-button>
          </div>
        </template>
        
        <el-table
          :data="householdList"
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column prop="communityName" label="小区名称" width="150" />
          <el-table-column prop="buildingName" label="楼栋名称" width="120" />
          <el-table-column prop="unitName" label="单元名称" width="100" />
          <el-table-column prop="roomNumber" label="房间号" width="100" />
          <el-table-column prop="ownershipType" label="产权类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getOwnershipTypeTag(row.ownershipType)">
                {{ getOwnershipTypeText(row.ownershipType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ownershipRatio" label="产权比例" width="100">
            <template #default="{ row }">
              {{ row.ownershipRatio }}%
            </template>
          </el-table-column>
          <el-table-column prop="isPrimaryOwner" label="主业主" width="80">
            <template #default="{ row }">
              <el-tag :type="row.isPrimaryOwner ? 'success' : 'info'">
                {{ row.isPrimaryOwner ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="certificateNumber" label="房产证号" width="180" />
          <el-table-column prop="certificateDate" label="发证日期" width="120" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEditHousehold(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteHousehold(row)">
                <el-icon><Delete /></el-icon>
                解除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <!-- 房户关联表单对话框 -->
    <el-dialog
      v-model="formVisible"
      :title="isEdit ? '编辑房户关联' : '新增房户关联'"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="小区" prop="communityId">
          <el-select
            v-model="formData.communityId"
            placeholder="请选择小区"
            clearable
            style="width: 100%"
            :loading="communityLoading"
            @change="handleCommunityChange"
            :disabled="isEdit"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.communityName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="楼栋" prop="buildingId">
          <el-select
            v-model="formData.buildingId"
            placeholder="请选择楼栋"
            clearable
            style="width: 100%"
            :loading="buildingLoading"
            @change="handleBuildingChange"
            :disabled="!formData.communityId || isEdit"
          >
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.buildingName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="单元" prop="unitId">
          <el-select
            v-model="formData.unitId"
            placeholder="请选择单元"
            clearable
            style="width: 100%"
            :loading="unitLoading"
            @change="handleUnitChange"
            :disabled="!formData.buildingId || isEdit"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="房间" prop="roomId">
          <el-select
            v-model="formData.roomId"
            placeholder="请选择房间"
            clearable
            style="width: 100%"
            :loading="roomLoading"
            :disabled="!formData.unitId || isEdit"
          >
            <el-option
              v-for="item in roomList"
              :key="item.id"
              :label="item.roomNumber"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="产权类型" prop="ownershipType">
          <el-select v-model="formData.ownershipType" placeholder="请选择产权类型" style="width: 100%">
            <el-option label="完全产权" :value="1" />
            <el-option label="共有产权" :value="2" />
            <el-option label="部分产权" :value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="产权比例" prop="ownershipRatio">
          <el-input-number
            v-model="formData.ownershipRatio"
            :min="0"
            :max="100"
            :precision="2"
            style="width: 100%"
          />
          <span class="unit-text">%</span>
        </el-form-item>
        
        <el-form-item label="主业主" prop="isPrimaryOwner">
          <el-switch
            v-model="formData.isPrimaryOwner"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        
        <el-form-item label="房产证号" prop="certificateNumber">
          <el-input
            v-model="formData.certificateNumber"
            placeholder="请输入房产证号"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="发证日期" prop="certificateDate">
          <el-date-picker
            v-model="formData.certificateDate"
            type="date"
            placeholder="请选择发证日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="抵押信息" prop="mortgageInfo">
          <el-input
            v-model="formData.mortgageInfo"
            type="textarea"
            :rows="3"
            placeholder="请输入抵押信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitForm" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { ownerHouseholdApi } from '@/api/ownerHousehold'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { householdApi } from '@/api/household'
import { dataScopeApi } from '@/api/property'

// 定义props和emits
interface Props {
  visible: boolean
  ownerData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 用户store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const formVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 加载状态
const communityLoading = ref(false)
const buildingLoading = ref(false)
const unitLoading = ref(false)
const roomLoading = ref(false)

// 计算属性
const isEdit = computed(() => !!currentHousehold.value)

// 当前编辑的房户关联
const currentHousehold = ref<any>(null)

// 房户关联列表
const householdList = ref<any[]>([])

// 加载房户关联列表
const loadHouseholdList = async () => {
  if (!props.ownerData?.id) return
  
  try {
    loading.value = true
    const response = await ownerHouseholdApi.getOwnerHouseholds(props.ownerData.id)
    console.log('房户关联列表API响应:', response)
    
    if (response.code === 200 && response.data) {
      householdList.value = response.data
      console.log('房户关联列表数据:', householdList.value)
      
      // 检查每个房户关联数据的字段
      householdList.value.forEach((item, index) => {
        console.log(`房户关联数据[${index}]:`, {
          id: item.id,
          householdId: item.householdId,
          communityId: item.communityId,
          buildingId: item.buildingId,
          unitId: item.unitId,
          roomId: item.roomId,
          roomNumber: item.roomNumber,
          ownershipType: item.ownershipType,
          ownershipRatio: item.ownershipRatio
        })
      })
    } else {
      ElMessage.error(response.message || '加载房户关联列表失败')
    }
  } catch (error) {
    console.error('加载房户关联列表失败:', error)
    ElMessage.error('加载房户关联列表失败')
  } finally {
    loading.value = false
  }
}

// 表单数据 - 遵循Element Plus组件编码规范，使用undefined而不是null
const formData = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  roomId: undefined as number | undefined,
  ownershipType: 1,
  ownershipRatio: 100, // 修复：改为数字类型，而不是字符串
  isPrimaryOwner: false,
  certificateNumber: '',
  certificateDate: '',
  mortgageInfo: ''
})

// 表单验证规则
const formRules: FormRules = {
  communityId: [
    { required: true, message: '请选择小区', trigger: 'change' }
  ],
  buildingId: [
    { required: true, message: '请选择楼栋', trigger: 'change' }
  ],
  unitId: [
    { required: true, message: '请选择单元', trigger: 'change' }
  ],
  roomId: [
    { required: true, message: '请选择房间', trigger: 'change' }
  ],
  ownershipType: [
    { required: true, message: '请选择产权类型', trigger: 'change' }
  ],
  ownershipRatio: [
    { required: true, message: '请输入产权比例', trigger: 'blur' }
  ],
  certificateNumber: [
    { required: true, message: '请输入房产证号', trigger: 'blur' }
  ],
  certificateDate: [
    { required: true, message: '请选择发证日期', trigger: 'change' }
  ]
}

// 四级联动数据
const communityList = ref<any[]>([])
const buildingList = ref<any[]>([])
const unitList = ref<any[]>([])
const roomList = ref<any[]>([])

// 获取产权类型标签
const getOwnershipTypeTag = (type: number) => {
  switch (type) {
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'info'
    default: return 'info'
  }
}

// 获取产权类型文本
const getOwnershipTypeText = (type: number) => {
  switch (type) {
    case 1: return '完全产权'
    case 2: return '共有产权'
    case 3: return '部分产权'
    default: return '未知'
  }
}

// 加载社区列表（根据数据权限）
const loadCommunityList = async () => {
  try {
    communityLoading.value = true
    
    // 获取用户数据权限信息
    const userDataScope = userStore.getUserDataScope()
    
    if (userDataScope.isSuperAdmin) {
      // 超级管理员可以看到所有社区
      const response = await communityApi.getCommunityList({ status: 1 })
      if (response.code === 200) {
        communityList.value = response.data || []
      }
    } else {
      // 物业公司管理员只能看到关联的社区
      const response = await dataScopeApi.getUserCommunities()
      if (response.code === 200 && response.data) {
        const communityIds = response.data
        if (communityIds.length > 0) {
          const communityResponse = await communityApi.getCommunityList({ 
            status: 1,
            ids: communityIds.join(',')
          })
          if (communityResponse.code === 200) {
            communityList.value = communityResponse.data || []
          }
        } else {
          communityList.value = []
        }
      }
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
    ElMessage.error('加载社区列表失败')
    communityList.value = []
  } finally {
    communityLoading.value = false
  }
}

// 小区变化处理
const handleCommunityChange = async (communityId: number, isEditMode = false) => {
  console.log('handleCommunityChange 被调用，communityId:', communityId, 'isEditMode:', isEditMode)
  
  // 编辑模式下不清空表单数据
  if (!isEditMode) {
    formData.buildingId = undefined
    formData.unitId = undefined
    formData.roomId = undefined
  }
  
  buildingList.value = []
  unitList.value = []
  roomList.value = []
  
  if (!communityId) {
    console.log('communityId为空，直接返回')
    return
  }
  
  try {
    buildingLoading.value = true
    console.log('开始加载楼栋数据，communityId:', communityId)
    const response = await buildingApi.getBuildingsByCommunity(communityId)
    console.log('楼栋API响应:', response)
    
    if (response.code === 200) {
      buildingList.value = response.data || []
      console.log('楼栋列表加载完成，数量:', buildingList.value.length)
    } else {
      console.error('楼栋API返回错误:', response.message)
      ElMessage.error(response.message || '加载楼栋列表失败')
      buildingList.value = []
    }
  } catch (error) {
    console.error('加载楼栋列表失败:', error)
    ElMessage.error('加载楼栋列表失败')
    buildingList.value = []
  } finally {
    buildingLoading.value = false
  }
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number, isEditMode = false) => {
  console.log('handleBuildingChange 被调用，buildingId:', buildingId, 'isEditMode:', isEditMode)
  
  // 编辑模式下不清空表单数据
  if (!isEditMode) {
    formData.unitId = undefined
    formData.roomId = undefined
  }
  
  unitList.value = []
  roomList.value = []
  
  if (!buildingId) {
    console.log('buildingId为空，直接返回')
    return
  }
  
  try {
    unitLoading.value = true
    console.log('开始加载单元数据，buildingId:', buildingId)
    const response = await unitApi.getUnitsByBuilding(buildingId)
    console.log('单元API响应:', response)
    
    if (response.code === 200) {
      unitList.value = response.data || []
      console.log('单元列表加载完成，数量:', unitList.value.length)
    } else {
      console.error('单元API返回错误:', response.message)
      ElMessage.error(response.message || '加载单元列表失败')
      unitList.value = []
    }
  } catch (error) {
    console.error('加载单元列表失败:', error)
    ElMessage.error('加载单元列表失败')
    unitList.value = []
  } finally {
    unitLoading.value = false
  }
}

// 单元变化处理
const handleUnitChange = async (unitId: number, isEditMode = false) => {
  console.log('handleUnitChange 被调用，unitId:', unitId, 'isEditMode:', isEditMode)
  
  // 编辑模式下不清空表单数据
  if (!isEditMode) {
    formData.roomId = undefined
  }
  
  roomList.value = []
  
  if (!unitId) {
    console.log('unitId为空，直接返回')
    return
  }
  
  try {
    roomLoading.value = true
    console.log('开始加载房间数据，unitId:', unitId)
    const response = await householdApi.getHouseholdsByUnit(unitId)
    console.log('房间API响应:', response)
    
    if (response.code === 200) {
      roomList.value = response.data || []
      console.log('房间列表加载完成，数量:', roomList.value.length)
    } else {
      console.error('房间API返回错误:', response.message)
      ElMessage.error(response.message || '加载房间列表失败')
      roomList.value = []
    }
  } catch (error) {
    console.error('加载房间列表失败:', error)
    ElMessage.error('加载房间列表失败')
    roomList.value = []
  } finally {
    roomLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    communityId: undefined,
    buildingId: undefined,
    unitId: undefined,
    roomId: undefined,
    ownershipType: 1,
    ownershipRatio: 100, // 修复：确保是数字类型
    isPrimaryOwner: false,
    certificateNumber: '',
    certificateDate: '',
    mortgageInfo: ''
  })
  
  buildingList.value = []
  unitList.value = []
  roomList.value = []
  
  formRef.value?.clearValidate()
}

// 新增房户关联
const handleAddHousehold = () => {
  currentHousehold.value = null
  resetForm()
  // 加载社区列表
  loadCommunityList()
  formVisible.value = true
}

// 编辑房户关联
const handleEditHousehold = async (row: any) => {
  console.log('开始编辑房户关联:', row)
  // 确保currentHousehold包含正确的ownerId和householdId
  currentHousehold.value = { 
    ...row,
    ownerId: props.ownerData?.id, // 确保包含业主ID
    householdId: row.householdId // 确保包含房户ID
  }
  
  // 先加载社区列表
  await loadCommunityList()
  console.log('社区列表加载完成:', communityList.value)
  
  // 根据householdId获取房户详细信息
  if (row.householdId) {
    try {
      console.log('获取房户详细信息，householdId:', row.householdId)
      const householdResponse = await householdApi.getHouseholdDetail(row.householdId)
      console.log('房户详细信息响应:', householdResponse)
      
      if (householdResponse.code === 200 && householdResponse.data) {
        const householdDetail = householdResponse.data
        console.log('房户详细信息:', householdDetail)
        console.log('房户详细信息字段检查:', {
          communityId: householdDetail.communityId,
          buildingId: householdDetail.buildingId,
          unitId: householdDetail.unitId,
          roomNumber: householdDetail.roomNumber
        })
        
        // 根据房户详细信息加载四级联动数据
        if (householdDetail.communityId) {
          console.log('加载楼栋数据，社区ID:', householdDetail.communityId)
          await handleCommunityChange(householdDetail.communityId, true)
          console.log('楼栋列表加载完成:', buildingList.value)
          
          if (householdDetail.buildingId) {
            console.log('加载单元数据，楼栋ID:', householdDetail.buildingId)
            await handleBuildingChange(householdDetail.buildingId, true)
            console.log('单元列表加载完成:', unitList.value)
            
            if (householdDetail.unitId) {
              console.log('加载房间数据，单元ID:', householdDetail.unitId)
              await handleUnitChange(householdDetail.unitId, true)
              console.log('房间列表加载完成:', roomList.value)
            }
          }
        }
        
        // 等待所有数据加载完成后再设置表单数据
        await nextTick()
        
        // 设置表单数据 - 使用房户详细信息中的四级联动数据
        const formDataToSet = {
          communityId: householdDetail.communityId,
          buildingId: householdDetail.buildingId,
          unitId: householdDetail.unitId,
          roomId: row.householdId, // 使用householdId作为roomId
          ownershipType: row.ownershipType,
          ownershipRatio: Number(row.ownershipRatio) || 100,
          isPrimaryOwner: row.isPrimaryOwner,
          certificateNumber: row.certificateNumber || '',
          certificateDate: row.certificateDate || '',
          mortgageInfo: row.mortgageInfo || ''
        }
        
        console.log('设置表单数据:', formDataToSet)
        Object.assign(formData, formDataToSet)
        
        // 再次等待DOM更新
        await nextTick()
        console.log('编辑对话框打开，表单数据:', formData)
        
        formVisible.value = true
      } else {
        console.error('房户详情API返回错误:', householdResponse)
        ElMessage.error('获取房户详细信息失败')
      }
    } catch (error) {
      console.error('获取房户详细信息失败:', error)
      ElMessage.error('获取房户详细信息失败')
    }
  } else {
    console.error('房户ID为空:', row)
    ElMessage.error('房户ID不能为空')
  }
}

// 删除房户关联
const handleDeleteHousehold = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要解除业主与房户"${row.communityName}${row.buildingName}${row.unitName}${row.roomNumber}"的关联吗？`,
      '确认解除关联',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端API删除关联
    const response = await ownerHouseholdApi.removeOwnerHousehold(props.ownerData?.id, row.householdId)
    if (response.code === 200) {
      ElMessage.success('解除关联成功')
      // 重新加载列表
      await loadHouseholdList()
    } else {
      ElMessage.error(response.message || '解除关联失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解除关联失败:', error)
      ElMessage.error('解除关联失败')
    }
  }
}

// 提交表单
const handleSubmitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      // 编辑模式 - 不传递ownerId和householdId，只更新可编辑字段
      const response = await ownerHouseholdApi.updateOwnerHousehold(currentHousehold.value?.id, {
        ownershipType: formData.ownershipType,
        ownershipRatio: formData.ownershipRatio,
        isPrimaryOwner: formData.isPrimaryOwner,
        certificateNumber: formData.certificateNumber,
        certificateDate: formData.certificateDate,
        mortgageInfo: formData.mortgageInfo
      })
      
      if (response.code === 200) {
        const index = householdList.value.findIndex(item => item.id === currentHousehold.value?.id)
        if (index > -1) {
          householdList.value[index] = {
            ...currentHousehold.value,
            ...formData,
            communityName: communityList.value.find(c => c.id === formData.communityId)?.communityName,
            buildingName: buildingList.value.find(b => b.id === formData.buildingId)?.buildingName,
            unitName: unitList.value.find(u => u.id === formData.unitId)?.unitName,
            roomNumber: roomList.value.find(r => r.id === formData.roomId)?.roomNumber
          }
        }
        ElMessage.success('更新成功')
        // 重新加载列表
        await loadHouseholdList()
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } else {
      // 新增模式
      const response = await ownerHouseholdApi.createOwnerHousehold({
        ownerId: props.ownerData?.id,
        householdId: formData.roomId,
        ownershipType: formData.ownershipType,
        ownershipRatio: formData.ownershipRatio,
        isPrimaryOwner: formData.isPrimaryOwner,
        certificateNumber: formData.certificateNumber,
        certificateDate: formData.certificateDate,
        mortgageInfo: formData.mortgageInfo
      })
      
      if (response.code === 200) {
        ElMessage.success('创建成功')
        // 重新加载列表
        await loadHouseholdList()
      } else {
        ElMessage.error(response.message || '创建失败')
      }
    }
    
    formVisible.value = false
    emit('success')
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('表单提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 监听对话框显示状态，加载房户关联列表
watch(() => props.visible, async (newVisible) => {
  if (newVisible && props.ownerData?.id) {
    // 同时加载房户关联列表和社区列表
    await Promise.all([
      loadHouseholdList(),
      loadCommunityList()
    ])
  }
})

// 初始化函数
const initializeData = async () => {
  if (props.ownerData?.id) {
    try {
      // 并行加载数据以提高性能
      await Promise.all([
        loadHouseholdList(),
        loadCommunityList()
      ])
    } catch (error) {
      console.error('初始化数据失败:', error)
      ElMessage.error('初始化数据失败')
    }
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  if (props.visible && props.ownerData?.id) {
    initializeData()
  }
})
</script>

<style scoped>
.owner-household-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.owner-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.unit-text {
  margin-left: 10px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}
</style>
